package com.goatrock.media.thisway.domain.service.impl;

import com.goatrock.media.thisway.domain.service.RetrievalService;
import com.goatrock.media.thisway.common.constants.ApplicationConstants;
import com.goatrock.media.thisway.common.model.Title;
import com.goatrock.media.thisway.domain.adapter.impl.BaseAdapterImpl;
import com.goatrock.media.thisway.domain.utils.MMMUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;

public class RetrievalServiceImpl implements RetrievalService{
    private BaseAdapterImpl bAdapter;
    private List extList;

    private Logger logger = Logger.getLogger(RetrievalServiceImpl.class);
    private Logger loggerMetrics = Logger.getLogger("METRICS");
    /*
     * Gets entire list of movies and stores them in a list of dto objects
     */
    public List getTitles(String[] mediaLocations){
        ArrayList<Title> titles = new ArrayList<Title>();
        int count = 0;
        if(mediaLocations == null){
            return null;
        }
        final long startTime = System.currentTimeMillis();

        for (int i=0;i<mediaLocations.length;i++){ //iterate through media locations
            logger.info("Loading Movies for location: " + mediaLocations[i]);

            if (new File(mediaLocations[i]).exists()){
                logger.info("Location exists!");
                //System.out.println("Location exists!");
                File folder = new File(mediaLocations[i]);
                File[] listOfFiles = folder.listFiles();
                String xmlPath = null;

                for (int j = 0;j<listOfFiles.length;j++){ //iterate through each piece of media
                    if (new File(listOfFiles[j].getPath()).exists() && (!listOfFiles[j].isFile())){
                        //System.out.println("Loading Movie for location: " + listOfFiles[j]);
                        logger.debug("loading movie for location:"+listOfFiles[j]);
                        Title tmpTitle = new Title();
                        xmlPath = listOfFiles[j].getPath() + "\\" + ApplicationConstants.MOVIE_INFO_FILE_NAME;
                        if (new File(xmlPath).exists()){
                            try{
                                tmpTitle = (Title) bAdapter.unmarshallXMLByPath(xmlPath, Title.class);
                            }catch(FileNotFoundException e){
                                logger.info("MyMovies.xml was unable to load.");
                            }
                            
                            tmpTitle.setBaseFileLocation(listOfFiles[j].getPath());
                            tmpTitle.setHasXMLFile(Boolean.TRUE);
                        }
                        tmpTitle = loadTitleInfo(tmpTitle,listOfFiles[j].getPath());
                        if (tmpTitle != null) {
                            if(tmpTitle.getHasXMLFile() == Boolean.FALSE){
                                tmpTitle.setLocalTitle(listOfFiles[j].getName());
                                tmpTitle.setSortTitle(listOfFiles[j].getName());
                            }
                            
                            tmpTitle.setMediaListerID(count);
                            count++;
                            titles.add(tmpTitle);
                        }
                    }
                }
            }
            
        }
        final long endTime = System.currentTimeMillis();
        final long totalTime = endTime-startTime;

        logger.info("***Successfully Loaded All Movies***\nNumber titles:"+titles.size());
        loggerMetrics.info("Load titles (time/total titles):"+totalTime+"/"+titles.size());

        Collections.sort(titles); // sort the list before returning it
        return titles;
    }

    private Title loadTitleInfo(Title title,String filePath){
        Boolean movieFoundFlag = Boolean.FALSE;
        if (new File(filePath + "\\" + ApplicationConstants.MOVIE_INFO_FOLDER_NAME)
                .exists()) {
            title.setHasFolderImage(Boolean.TRUE);
        }

        if (new File(filePath + "\\" + ApplicationConstants.MOVIE_INFO_BACKDROP_NAME)
                .exists()) {
            title.setHasBackdropImage(Boolean.TRUE);
        }

        File[] files = new File(filePath).listFiles();
        for (int i = 0; i<files.length;i++){
            String filename = files[i].getName();
            String ext = filename.substring(filename.lastIndexOf('.')+1,filename.length()).toLowerCase();
            if (extList.contains(ext)){
                movieFoundFlag = Boolean.TRUE;
                title.setMovieFileNames(title.addElementToStringArray(filename, title.getMovieFileNames()));
                title.setTitleSize(title.addElementToStringArray(MMMUtils.formatSize(files[i].length()), title.getTitleSize()));
            }
        }
        if (movieFoundFlag.equals(Boolean.FALSE)) {
            return null;
        }
        return title;
    }

    public BaseAdapterImpl getbAdapter() {
        return bAdapter;
    }

    public void setbAdapter(BaseAdapterImpl bAdapter) {
        this.bAdapter = bAdapter;
    }

    public List getExtList() {
        return extList;
    }

    public void setExtList(List extList) {
        this.extList = extList;
    }

    
}
